<?php
defined('G_IN_SYSTEM')or exit('no');
System::load_app_class("base");
include('emoji.php');
class shaidan extends base {
	public $db;
	public function __construct(){
		parent::__construct();
		$this->db=System::load_sys_class('model');

	}

	public function unserializeArray($array){
		foreach ($array as $key => $value) {
			if(array_key_exists('info',$value))			{$array[$key]['info']=unserialize($value['info']);}
			if(array_key_exists('q_user',$value))		{$array[$key]['q_user']=unserialize($value['q_user']);}
			if(array_key_exists('picarr',$value))		{$array[$key]['picarr']=unserialize($value['picarr']);}
			if(array_key_exists('q_content',$value))	{$array[$key]['q_content']=unserialize($value['q_content']);}
		}
		return $array;
	}
	//晒单分享
	public function all_shaidan(){
		$num=10;
		$total=$this->db->GetCount("select * from `@#_shaidan`");
		$page=System::load_sys_class('page');
		if(isset($_POST['page'])){
			$pagenum=$_POST['page'];
		}else{$pagenum=1;}
		$page->config($total,$num,$pagenum,"0");
		if($pagenum>$page->page){
			$pagenum=$page->page;
		}
		$shaidan=$this->db->GetPage("select * from `@#_shaidan` order by `sd_id` DESC",array("num"=>$num,"page"=>$pagenum,"type"=>1,"cache"=>0));
		$yeshu=ceil($total/$num);
		$isNoData=false;
		if($pagenum >= $yeshu){
			$isNoData=true;
		}
		foreach($shaidan as $sk=>$sv){
			$shaidan[$sk]['sd_title'] = strip_tags($shaidan[$sk]['sd_title']);
			$shaidan[$sk]['sd_user'] = $this->getUserInfo($sv['sd_userid']);
			$shaidan[$sk]['sd_content'] = strip_tags($shaidan[$sk]['sd_content']);
//			if(get_device_type() == 'ios'){
//				$shaidan[$sk]['sd_content'] = emoji_unified_to_softbank(strip_tags($shaidan['sd_content']));
//			}else if(get_device_type() == 'android'){
//				$shaidan[$sk]['sd_content'] = emoji_unified_to_google(strip_tags($shaidan['sd_content']));
//			}
		}
		if ($shaidan) {

			$data = array("isNoData"=>$isNoData,'info'=>$shaidan);
			$this->success($data);

		}else{
			$this->success(array("isNoData"=>true,'info'=>null));
		}
		
	}

	public function item_shaidan(){
			$sid = $_POST['sid'];
		if($sid){
			$num=10;
			$total=$this->db->GetCount("select * from `@#_shaidan` where `sd_shopsid`=$sid");
			$page=System::load_sys_class('page');
			if(isset($_POST['page'])){
				$pagenum=$_POST['page'];
			}else{$pagenum=1;}
			$page->config($total,$num,$pagenum,"0");
			if($pagenum>$page->page){
				$pagenum=$page->page;
			}
			$shaidan=$this->db->GetPage("select * from `@#_shaidan` where `sd_shopsid`=$sid order by `sd_id` DESC",array("num"=>$num,"page"=>$pagenum,"type"=>1,"cache"=>0));
			$yushu=$total%$num;
			$yeshu=floor($total/$num)+1;
			$isNoData=false;
			if($yushu>0 && $yeshu==$pagenum){
				//$sum=$yushu;
				$isNoData=true;
			}

			foreach($shaidan as $sk=>$sv){
				$shaidan[$sk]['sd_title'] = strip_tags($shaidan[$sk]['sd_title']);
				$shaidan[$sk]['sd_user'] = $this->getUserInfo($sv['sd_userid']);
				$shaidan[$sk]['sd_content'] = strip_tags($shaidan[$sk]['sd_content']);
//				if(get_device_type() == 'ios'){
//					$shaidan[$sk]['sd_content'] = emoji_unified_to_softbank(strip_tags($shaidan['sd_content']));
//
//				}else if(get_device_type() == 'android'){
//					$shaidan[$sk]['sd_content'] = emoji_unified_to_google(strip_tags($shaidan['sd_content']));
//				}
			}
			if ($shaidan) {
				$data = array("isNoData"=>$isNoData,'info'=>$shaidan);
				$this->success($data);
			}else{
				$this->failed('获取晒单失败');
			}
		}else{
			$this->failed("获取晒单信息失败");
		}
	}
	//获取特定用户的晒单
	public function user_shaidan(){
		$uid = $_POST['uid'];
		$token = $this->rsa->decrypt($_POST['token']);
		$time = $_POST['time'];
		$trustToken = md5(_getcookie("token").$time);
//		if($token == $trustToken && $uid) {
			$num = 10;
			$total = $this->db->GetCount("select * from `@#_shaidan` where `sd_userid` = $uid");
			$page = System::load_sys_class('page');
			if (isset($_POST['page'])) {
				$pagenum = $_POST['page'];
			} else {
				$pagenum = 1;
			}
			$page->config($total, $num, $pagenum, "0");
			if ($pagenum > $page->page) {
				$pagenum = $page->page;
			}
			$shaidan = $this->db->GetPage("select * from `@#_shaidan` where `sd_userid` = $uid  order by `sd_id` DESC", array("num" => $num, "page" => $pagenum, "type" => 1, "cache" => 0));

			$yushu = $total % $num;
			$yeshu = floor($total / $num) + 1;
			$isNoData = false;
			if ($yushu > 0 && $yeshu == $pagenum) {
				$isNoData = true;
			}

			foreach ($shaidan as $sk => $sv) {
				$shaidan[$sk]['sd_title'] = strip_tags($shaidan[$sk]['sd_title']);
				$shaidan[$sk]['sd_user'] = $this->getUserInfo($sv['sd_userid']);
				$shaidan[$sk]['sd_content'] = strip_tags($shaidan[$sk]['sd_content']);
			}
			if ($shaidan) {
				$data = array("isNoData" => $isNoData, 'info' => $shaidan);
				$this->success($data);
			} else {
				$this->failed('获取晒单失败');
			}
//		}else{
//			$this->failed('无权访问');
//		}

	}

	public function user_no_shaidan(){

		$uid = $_POST['uid'];
//			$token = $this->rsa->decrypt($_POST['token']);
//			$time = $_POST['time'];
//			$trustToken = md5(_getcookie("token").$time);
//			if($token == $trustToken && $uid){
		$ids = $this->db->GetList("select `sd_shopid` from `qy_shaidan`  where `sd_userid`=$uid");

			$shaidanids = "";
			foreach ($ids as $key => $value) {
				$shaidanids .= $value['sd_shopid'] . ",";
			}
			$shaidanids = trim($shaidanids, ',');
		$time = time() - 300;
		if($ids) {
			$totalSql = "select * from `@#_member_go_record` where `uid`='$uid' and `shopid` not in ($shaidanids) and `huode`>'10000000' and `time` < $time  GROUP BY `shopid`";
			$sql = "SELECT * FROM ((SELECT `shopid`,SUM(`gonumber`) as `q_buy_count` FROM `@#_member_go_record`  where `uid` = $uid and `time` < $time and shopid in
				(SELECT `shopid` FROM `@#_member_go_record` where `uid` = $uid and `huode`>'10000000' and `time` < $time and `shopid` not in($shaidanids) group by `shopid`)
                group by `shopid` ORDER BY `shopid` DESC) as A )
                INNER JOIN
                (SELECT `thumb`,`qishu`,`title`,`zongrenshu`,`q_user_code`,`q_user`,`q_end_time`,`id`,`q_content`,`q_counttime`  FROM `@#_shoplist`
                WHERE  id in(SELECT `shopid` FROM `@#_member_go_record`  where uid = $uid and `time` < $time and `shopid` not in($shaidanids) group by `shopid`) order by `id` desc)  as B
		    ON A.shopid = B.id";
		}else{
			$totalSql = "select * from `@#_member_go_record` WHERE `uid` = '$uid' AND `huode` > '10000000' and `time` < $time GROUP BY `shopid`";
			$sql = "SELECT * FROM ((SELECT `shopid`,SUM(`gonumber`) as `q_buy_count` FROM `@#_member_go_record`  where `uid` = $uid and `time` < $time and shopid in
				(SELECT `shopid` FROM `@#_member_go_record` where `uid` = $uid and `huode`>'10000000' and `time` < $time group by `shopid`)
                group by `shopid` ORDER BY `shopid` DESC) as A )
                INNER JOIN
                (SELECT `thumb`,`qishu`,`title`,`zongrenshu`,`q_user_code`,`q_user`,`q_end_time`,`id`,`q_content`,`q_counttime`  FROM `@#_shoplist`
                WHERE  id in(SELECT `shopid` FROM `@#_member_go_record`  where uid = $uid and `time` < $time group by `shopid`) order by `id` desc)  as B
		    ON A.shopid = B.id";
		}
			$total = $this->db->GetCount($totalSql);
			$page = System::load_sys_class('page');
			if (isset($_POST['page'])) {
				$pagenum = $_POST['page'];
			} else {
				$pagenum = 1;
			}
			$page->config($total, 10, $pagenum, "0");

			$record = $this->db->GetPage($sql, array("num" => 10, "page" => $pagenum, "type" => 1, "cache" => 0));
//		$this->success($record);
//
			$isNoData = false;
			if ($pagenum >= ($total / 10)) {
				$isNoData = true;
			}
			if ($record) {
				$record = $this->unserializeArray($record);
				$this->success(array("info" => $record, "isNoData" => $isNoData));
			} else {
				$this->failed('未晒单记录为空！');
			}

//		}
//			else{
//				$this->failed('无权访问');
//			}
	}
	public  function getUserInfo($uid) {
		$user = $this->db->GetOne("select * from `@#_member` where `uid` = $uid");
		$array = array('uid'=>$uid,'username'=>$user['username'],'img'=>$user['img']);
		if(!user){
			return array('uid'=>$uid,'username'=>"匿名用户",'img'=>"photo/member.jpg");
		}
		return $array;
	}
	//晒单详情
	public function detail(){
		$sd_id=$_POST['sd_id'];//晒单Id
		$uid = $_POST['uid'];
		$id = $_POST['id'];
		//$sd_id=1;//晒单Id
		$shaidan=$this->db->GetOne("SELECT * FROM (
SELECT * FROM  (SELECT `id`,`thumb`,`title`,`zongrenshu`,`qishu`,`q_user`,`q_user_code`,`q_end_time`,`q_counttime`,`q_uid`,`q_content`,`money` FROM `@#_shoplist` AS t WHERE id = $id) AS A
INNER JOIN
(SELECT sum(`moneycount`) AS `moneycount`,`shopid` FROM `@#_member_go_record` AS w WHERE `uid` = $uid AND `shopid` = $id ) AS B
)
AS C INNER JOIN
(SELECT * FROM `@#_shaidan` AS c WHERE `sd_id` = $sd_id) AS D");
		$shaidan['q_user'] = unserialize($shaidan['q_user']);
		$shaidan['sd_content'] = strip_tags($shaidan['sd_content']);
//		if(get_device_type() == 'ios'){
//			$shaidan['sd_content'] = emoji_unified_to_softbank(strip_tags($shaidan['sd_content']));
//		}else if(get_device_type() == 'android'){
//			$shaidan['sd_content'] = emoji_unified_to_google(strip_tags($shaidan['sd_content']));
//		}
		$shaidan['q_content'] = $shaidan['q_content'] ? unserialize($shaidan['q_content']): null;

		if(!$shaidan){
			$this->falied("页面错误");
		}else{

			$this->success($shaidan);
		}
		
	}
    public function zan_shaidan(){
        $sd_id = $_POST['sd_id'];
        $record = $this->db->GetOne("SELECT `sd_id` FROM `@#_shaidan` WHERE `sd_id` = $sd_id");
        if($record){
            $result = $this->db->Query("UPDATE `@#_shaidan` SET `sd_zhan` = `sd_zhan` + 1 where `sd_id` = $sd_id");
            if($result)
            {
                $this->success("已赞");
            }else{
                $this->failed("未成功");
            }
        }else{
            $this->failed("无此记录");
        }
    }

	public function  add_shaidan(){
		$uid = $_POST['uid'];
		$token = $this->rsa->decrypt($_POST['token']);
		$time = $_POST['time'];
		$trustToken = md5(_getcookie("token").$time);
		//	if($token == $trustToken && $uid) {
		$id = $_POST['id'];
		$item = $this->db->GetOne("SELECT * FROM `@#_shoplist` WHERE `id` = $id");
		$check = $this->db->GetOne("SELECT * FROM `@#_shaidan` WHERE `sd_shopid` = $id");
		if($check){
			$this->failed("该商品已晒单");
		}
		if(get_device_type() == 'ios'){
			$comment = emoji_softbank_to_unified($_POST['comment']);
		}else if(get_device_type() == 'android'){
			$comment = emoji_google_to_unified($_POST['comment']);
		}
		$ip = _get_ip_dizhi();
		$qishu = $item['qishu'];
		$sid = $item['sid'];
		$title = $_POST['title'];
		$photolist = '';
		$time = time();
		if(!empty($_FILES)){
			$i = 0;
			foreach($_FILES as $key => $value){
				$file = 'pic_'.$i;
				$i++;
				System::load_sys_class('upload','sys','no');
				upload::upload_config(array('png','jpg','jpeg'),5000000,'shaidan');
				upload::go_upload($_FILES[$file],false);
				if(!upload::$ok){
					$this->failed(upload::$error);
				}else {
					$img = upload::$filedir ."/". upload::$filename;
					$photolist.="shaidan/".$img.';';
				}
			}
			$size=getimagesize(G_UPLOAD."/shaidan/".$img);
			$width=220;
			$height=$size[1]*($width/$size[0]);
			$src_houzhui = upload::thumbs($width,$height,false,G_UPLOAD."/shaidan/".$img);
			$thumbs="shaidan/".$img."_".intval($width).intval($height).".".$src_houzhui;
			$insertSql = "INSERT INTO `@#_shaidan`
(sd_userid,sd_shopid,sd_qishu,sd_ip,sd_thumbs,sd_title,sd_content,sd_photolist,sd_zhan,sd_ping,sd_time,sd_shopsid,status,grade,score) VALUE
('$uid','$id','$qishu','$ip','$thumbs','$title','$comment','$photolist','0','0','$time','$sid','0','D','1')";
			$result = $this->db->Query($insertSql);
			if($result){
				$this->success("OK");
			}else{
				$this->failed("晒单失败");
			}
		}

		//	}else{
		//		$this->failed('无权访问');
		//	}
	}
}

function get_device_type()
{
 $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
 $type = 'other';
 //分别进行判断
 if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
{
 $type = 'ios';
 } 
  
 if(strpos($agent, 'android'))
{
 $type = 'android';
 }
 return $type;
}
?>